package com.huangkailong.gitimgbed.util;

import cn.hutool.core.thread.NamedThreadFactory;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author huangkl
 * @since 1.0.0
 */
public class ToastUtil {
    private static final Stage STAGE =new Stage();
    private static final Label LABEL =new Label();
    private static final ScheduledExecutorService EXECUTOR;

    static {
        //舞台透明
        STAGE.initStyle(StageStyle.TRANSPARENT);
        EXECUTOR = new ScheduledThreadPoolExecutor(1, new NamedThreadFactory("toast-task-", false));
    }


    /**
     * 显示消息，3 秒
     *
     * @param msg 消息
     */
    public static void toast(String msg) {
        toast(msg, 3, TimeUnit.SECONDS);
    }

    /**
     * 显示消息
     *
     * @param msg 要显示的信息
     * @param time 时间
     * @param unit 时间单位
     */
    public static void toast(String msg, long time, TimeUnit unit) {
        LABEL.setText(msg);
        EXECUTOR.schedule(()->{
            Platform.runLater(STAGE::close);
        }, time, unit);
        init(msg);
        STAGE.show();
    }

    /**
     * 设置消息
     *
     * @param msg 消息
     */
    private static void init(String msg) {
        //默认信息
        Label label=new Label(msg);
        //label透明,圆角
        label.setStyle("-fx-background: rgba(56,56,56,0.7);-fx-border-radius: 25;-fx-background-radius: 25");
        //消息字体颜色
        label.setTextFill(Color.rgb(225,255,226));
        label.setPrefHeight(50);
        label.setPadding(new Insets(15));
        label.setAlignment(Pos.CENTER);
        label.setFont(new Font(20));
        Scene scene=new Scene(label);
        //场景透明
        scene.setFill(null);
        STAGE.setScene(scene);
    }
}